package com.zbkj.crmeb.chant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.zbkj.crmeb.chant.dao.ChannelMemberLevelDao;
import com.zbkj.crmeb.chant.model.ChannelMemberLevel;
import com.zbkj.crmeb.chant.request.MemberLevelRequest;
import com.zbkj.crmeb.chant.service.ChannelMemberLevelService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.model.UserMemberLevelRecord;
import com.zbkj.crmeb.user.service.UserMemberLevelRecordService;
import com.zbkj.crmeb.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 商户会员等级表 服务实现类
 * </p>
 *
 * @author wuzp
 * @since 2022-06-13
 */
@Service
public class ChannelMemberLevelServiceImpl extends ServiceImpl<ChannelMemberLevelDao, ChannelMemberLevel> implements ChannelMemberLevelService {

    @Resource
    private ChannelMemberLevelDao channelMemberLevelDao;
    @Autowired
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> updateMemberLevel(MemberLevelRequest request) {
        synchronized (request.getMerId().toString().intern()) {
            ChannelMemberLevel memberLevel = this.getById(request.getId());
            if(memberLevel == null){
                throw new CrmebException("该等级会员不存在");
            }
            switch (memberLevel.getLevel()){
                case 1:
                    if(request.getPriceLadder() != 1){
                        throw new CrmebException("一级会员价格阶梯只能选择售价类型");
                    }
                    if(memberLevel.getCondition().compareTo(request.getCondition()) != 0){
                        throw new CrmebException("一级会员升级条件不能修改");
                    }
                    if(request.getStatus() == 0){
                        throw new CrmebException("一级会员无法关闭");
                    }
                    break;
                case 2:
                    List<ChannelMemberLevel> memberLevelList = getMemberLevelList(0,request.getMerId(),null);
                    ChannelMemberLevel firstLevel = memberLevelList.stream().filter(e -> e.getLevel() == 1).collect(Collectors.toList()).get(0);
                    if(request.getCondition().compareTo(firstLevel.getCondition()) < 1){
                        throw new CrmebException("二级会员升级条件必须大于一级会员");
                    }
                    ChannelMemberLevel threeLevel = memberLevelList.stream().filter(e -> e.getLevel() == 3).collect(Collectors.toList()).get(0);
                    if(request.getCondition().compareTo(threeLevel.getCondition()) > -1){
                        throw new CrmebException("二级会员升级条件必须小于三级会员");
                    }
                    break;
                case 3:
                    List<ChannelMemberLevel> memberLevels = getMemberLevelList(0,request.getMerId(), Collections.singletonList(2));
                    ChannelMemberLevel channelMemberLevel = memberLevels.get(0);
                    if(request.getCondition().compareTo(channelMemberLevel.getCondition()) < 1){
                        throw new CrmebException("三级会员升级条件必须大于二级会员");
                    }
                    break;
                default:
                    break;
            }
            if(memberLevel.getLevel() != 1 && request.getPriceLadder() == 1){
                throw new CrmebException("只有一级会员能选择售价类型");
            }
            List<ChannelMemberLevel> memberLevelList = getMemberLevelList(0, request.getMerId(), null);
            for (ChannelMemberLevel level : memberLevelList) {
                if(!Objects.equals(level.getId(), request.getId()) && level.getName().equals(request.getName())){
                    throw new CrmebException("该等级名称已存在");
                }
            }
            if(!Objects.equals(request.getStatus(), memberLevel.getStatus())){
                if(request.getStatus() == 0){
                    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(User::getLevel,memberLevel.getLevel()).eq(User::getMerId,request.getMerId());
                    int count = userService.count(lambdaQueryWrapper);
                    if(count>0){
                        throw new CrmebException("已有用户成为该等级会员，不能关闭");
                    }
                }else {
                    userService.updateMemberLevel(memberLevel, request.getCondition(), request.getMerId());
                }
            }else {
                if(request.getCondition().compareTo(memberLevel.getCondition()) < 0){
                    userService.updateMemberLevel(memberLevel, request.getCondition(), request.getMerId());
                }
            }

            if(memberLevel.getMerId() == 0){
                Integer level = memberLevel.getLevel();
                memberLevel = new ChannelMemberLevel();
                BeanUtils.copyProperties(request,memberLevel,"id");
                memberLevel.setLevel(level);
            }else {
                BeanUtils.copyProperties(request,memberLevel);
            }
            return this.saveOrUpdate(memberLevel) ? CommonResult.success() : CommonResult.failed();
        }
    }

    @Override
    public CommonResult<String> updateMemberLevelStatus(Integer id, Integer status, Integer merId) {
        ChannelMemberLevel memberLevel = this.getById(id);
        if(memberLevel == null){
            throw new CrmebException("该等级会员不存在");
        }
        if(Objects.equals(status, memberLevel.getStatus())){
            throw new CrmebException("参数异常");
        }
        if(status == 0){
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getLevel,memberLevel.getLevel()).eq(User::getMerId,merId);
            int count = userService.count(lambdaQueryWrapper);
            if(count>0){
                throw new CrmebException("已有用户成为该等级会员，不能关闭");
            }
        }else {
            userService.updateMemberLevel(memberLevel, memberLevel.getCondition(), merId);
        }
        if(memberLevel.getMerId() == 0){
            memberLevel.setId(null);
            memberLevel.setMerId(merId);
            memberLevel.setCreateTime(null);
        }
        memberLevel.setStatus(status);
        return this.saveOrUpdate(memberLevel) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public List<ChannelMemberLevel> getMemberLevelList(Integer type,Integer merId,List<Integer> levelList) {
        List<Integer> merIdList = Stream.of(0, merId).collect(Collectors.toList());
        List<ChannelMemberLevel> list = channelMemberLevelDao.getMemberLevelList(merIdList,levelList);
        if(type == 1){
            list = list.stream().filter(e->e.getStatus() == 1).collect(Collectors.toList());
        }
        return list.stream().sorted(Comparator.comparing(ChannelMemberLevel::getLevel)).collect(Collectors.toList());
    }

    @Override
    public List<ChannelMemberLevel> getMemberLevelList(Integer merId) {
        List<ChannelMemberLevel> request = this.lambdaQuery().eq(ChannelMemberLevel::getStatus, 1)
                .eq(ChannelMemberLevel::getMerId, merId).orderByAsc(ChannelMemberLevel::getLevel).list();
        return request;
    }


}
